package com.scnu.edu.controller;

import com.scnu.edu.dto.MovieDTO;
import com.scnu.edu.entity.Movie;
import com.scnu.edu.entity.User;
import com.scnu.edu.service.MovieService;
import com.scnu.edu.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
public class IndexController {
    @Autowired
    private MovieService movieService;
    
    @Resource
    private UserService userService;

    @RequestMapping("/")
    public String home() {
        return "redirect:/index";
    }

    @RequestMapping("/index")
    public String index(@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                       @RequestParam(name = "title", defaultValue = "") String title,
                       @RequestParam(name = "category", defaultValue = "") String category,
                       Model model) {
        int pageSize = 4;
        Map<String, Object> map = movieService.queryPage(title, category, pageNo, pageSize);
        
        // 直接使用MovieService.queryPage()返回的MovieDTO列表
        List<MovieDTO> movieDTOList = (List<MovieDTO>) map.get("records");
        
        model.addAttribute("currentPage", pageNo);
        model.addAttribute("pageCount", map.get("pageCount"));
        model.addAttribute("pageSize", pageSize);
        model.addAttribute("title", title);
        model.addAttribute("category", category);
        model.addAttribute("movieList", movieDTOList);
        model.addAttribute("categories", movieService.findCategories());
        return "index";
    }

    @RequestMapping("/login")
    public String toLogin() {
        return "login";
    }

    @RequestMapping("/register")
    public String toRegister() {
        return "register";
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session) {
        session.removeAttribute("user");
        return "redirect:/index";
    }

    @RequestMapping("/doLogin")
    @ResponseBody
    public String doLogin(String username, String password, HttpSession session) {
        User user = userService.login(username, password);
        if (user != null) {
            user.setPassword(""); // 安全处理
            session.setAttribute("user", user);

            // 登录时检查VIP状态（处理可能未更新的情况）
            if (user.getIsVip() != null && user.getIsVip()) {
                Date now = new Date();
                if (user.getVipExpireTime() != null && user.getVipExpireTime().before(now)) {
                    // VIP已过期，更新状态
                    user.setIsVip(false);
                    userService.updateById(user);
                    session.setAttribute("user", user);
                }
            }
            return "success";
        } else {
            return "用户名或密码错误!";
        }
    }

    @RequestMapping("/doRegister")
    @ResponseBody
    public String doRegister(User user) {
        User existUser = userService.getById(user.getUsername());
        if (existUser != null) {
            return "该用户名已被注册！";
        }
        if (userService.save(user)) {
            return "注册成功！";
        } else {
            return "注册失败！";
        }
    }

    @GetMapping("/movie/ranking/weekly")
    public String weeklyRanking(Model model) {
        model.addAttribute("type", "weekly");
        model.addAttribute("movies", movieService.getWeeklyRanking());
        model.addAttribute("monthlyRanking", movieService.getMonthlyRanking());
        model.addAttribute("ratingRanking", movieService.getRatingRanking());
        return "movie/ranking";
    }

    @GetMapping("/movie/ranking/monthly")
    public String monthlyRanking(Model model) {
        model.addAttribute("type", "monthly");
        model.addAttribute("movies", movieService.getMonthlyRanking());
        model.addAttribute("weeklyRanking", movieService.getWeeklyRanking());
        model.addAttribute("ratingRanking", movieService.getRatingRanking());
        return "movie/ranking";
    }

    @GetMapping("/movie/ranking/all")
    public String allRanking(Model model) {
        model.addAttribute("type", "all");
        model.addAttribute("movies", movieService.getAllTimeRanking());
        model.addAttribute("weeklyRanking", movieService.getWeeklyRanking());
        model.addAttribute("monthlyRanking", movieService.getMonthlyRanking());
        return "movie/ranking";
    }

    @GetMapping("/movie/ranking/rating")
    public String ratingRanking(Model model) {
        model.addAttribute("type", "rating");
        model.addAttribute("movies", movieService.getRatingRanking());
        model.addAttribute("weeklyRanking", movieService.getWeeklyRanking());
        model.addAttribute("monthlyRanking", movieService.getMonthlyRanking());
        return "movie/ranking";
    }
}